/***************************************************************************
 *   TCP/IP client socket HTTP reader test                                 *
 *                                                                         *
 *   Copyright (C) 2004 by Tyler Montbriand                                *
 *   tsm@accesscomm.ca                                                     *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include "SDL_rwhttp.h"

static int strissomething(const char *str, int (*fn)(int));

#define STRISDIGIT(str) strissomething(str,isdigit)
#define STRISSPACE(str) strissomething(str,isspace)

int main(int argc, char *argv[])
{
  int bread,port=80;
  char buf[256];
  SDL_RWops *rw;

  if((argc<3) || (argc>4))
  {
    fprintf(stderr,"Syntax:  test-http some.site /path/file.html [port]\n");
    return(1);
  }

  if(argc==4)
  {
    if(!STRISDIGIT(argv[3]))
    {
      fprintf(stderr,"Port \"%s\" is not a digit\n",argv[3]);
      return(1);
    }

    port=atoi(argv[3]);
    if((port<=0)||(port>65535))
    {
      fprintf(stderr,"Port %d is out of TCP bounds\n",port);
      return(1);
    }
  }

  if(argv[2][0]!='/')
  {
    fprintf(stderr,"Path \"%s\" does nto begin with a /\n");
    return(1);
  }

  rw=SDL_RWFromHTTP(NULL,argv[1],argv[2],port);
  if(rw==NULL)
  {
    fprintf(stderr,"Couldn't open HTTP RWops\n");
    return(2);
  }

  while((bread=SDL_RWread(rw,&buf,1,256))>0)
    fwrite(buf,bread,1,stdout);

  SDL_RWclose(rw);

  return(0);
}

static int strissomething(const char *str, int (*fn)(int))
{
  if((str==NULL)||(fn==NULL)) return(0);
  if(str[0]=='\0') return(0);

  while((*str)!='\0')
  {
    if(!fn(*str))
      return(0);
    str++;
  }

  return(1);
}
